"use client";

import { Card, Button, Descriptions, Tag, Space, App } from "antd";
import { useRouter } from "next/navigation";
import { api } from "~/trpc/react";
import { useSession } from "next-auth/react";
import type { Course, CourseInvitation, User } from "@prisma/client";

interface JoinCourseProps {
  invitation: CourseInvitation & {
    course: Course & {
      teacher: Pick<User, "id" | "name">;
    };
  };
}

export function JoinCourse({ invitation }: JoinCourseProps) {
  const router = useRouter();
  const { message } = App.useApp();
  const { data: session } = useSession();

  const joinMutation = api.courses.joinCourse.useMutation({
    onSuccess: () => {
      void message.success("成功加入课程！");
      // 根据用户角色决定跳转页面
      router.push("/my-courses");
    },
    onError: (error) => {
      void message.error(error.message || "加入课程失败");
    },
  });

  const handleJoin = async () => {
    try {
      await joinMutation.mutateAsync({
        invitationId: invitation.id,
      });
    } catch (error) {
      // 错误已在onError回调中处理
    }
  };

  return (
    <Card>
      <div className="space-y-8">
        <div>
          <h2 className="text-2xl font-bold mb-4">{invitation.course.title}</h2>
          <Descriptions column={1}>
            <Descriptions.Item label="课程描述">
              {invitation.course.description || "暂无描述"}
            </Descriptions.Item>
            <Descriptions.Item label="课程目标">
              {invitation.course.objectives || "暂无课程目标"}
            </Descriptions.Item>
            <Descriptions.Item label="课程教师">
              {invitation.course.teacher.name}
            </Descriptions.Item>
            <Descriptions.Item label="邀请链接有效期">
              <Tag color={invitation.expiresAt < new Date() ? 'error' : 'success'}>
                {invitation.expiresAt.toLocaleString()}
              </Tag>
            </Descriptions.Item>
          </Descriptions>
        </div>

        <div className="flex justify-start">
          <Space>
            <Button onClick={() => router.back()}>返回</Button>
            <Button
              type="primary"
              onClick={handleJoin}
              loading={joinMutation.isLoading}
              disabled={invitation.expiresAt < new Date()}
            >
              加入课程
            </Button>
          </Space>
        </div>
      </div>
    </Card>
  );
}
